package com.flux.ui.widget

import android.content.Context
import android.support.v7.widget.AppCompatEditText
import android.util.AttributeSet
import android.view.MotionEvent

/**
 * 解决ScrollView滑动冲突问题
 * Created on 2018/3/2.
 *
 * @author Yang
 */
class ScrollEditText : AppCompatEditText {

    //滑动距离的最大边界
    private var mOffsetHeight: Int = 0

    //是否到顶或者到底的标志
    private var mBottomFlag = false

    constructor(context: Context) : super(context) {
        init()
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        init()
    }

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        init()
    }

    private fun init() {}

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)

        //获取上内边距
        val paddingTop = totalPaddingTop
        //获取下内边距
        val paddingBottom = totalPaddingBottom
        //获得控件的实际高度
        val mHeight= height
        //获得内容面板
        val mLayout = layout
        //获得内容面板的高度
        val mLayoutHeight = mLayout.height

        //计算滑动距离的边界
        mOffsetHeight = mLayoutHeight + paddingTop + paddingBottom - mHeight
    }

    override fun dispatchTouchEvent(event: MotionEvent): Boolean {
        //如果是新的按下事件，则对mBottomFlag重新初始化
        if (event.action == MotionEvent.ACTION_DOWN) mBottomFlag = false
        //如果已经不要这次事件，则传出取消的信号，这里的作用不大
        if (mBottomFlag) event.action = MotionEvent.ACTION_CANCEL
        return super.dispatchTouchEvent(event)
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        val result = super.onTouchEvent(event)
        //如果是需要拦截，则再拦截，这个方法会在onScrollChanged方法之后再调用一次
        if (!mBottomFlag) parent.requestDisallowInterceptTouchEvent(true)
        return result
    }

    override fun onScrollChanged(horiz: Int, vert: Int, oldHoriz: Int, oldVert: Int) {
        super.onScrollChanged(horiz, vert, oldHoriz, oldVert)
        if (vert == mOffsetHeight || vert == 0) {
            //这里触发父布局或祖父布局的滑动事件
            parent.requestDisallowInterceptTouchEvent(false)
            mBottomFlag = true
        }
    }
}